package sjtu.ist.warehouse4ws.jcr;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringBufferInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;


import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;

import org.springmodules.jcr.JcrCallback;
import org.springmodules.jcr.JcrTemplate;

import sjtu.ist.warehouse4ws.model.ModelFilePojo;
import sjtu.ist.warehouse4ws.model.Modelgroup;
import sjtu.ist.warehouse4ws.model.VisionInfoPojo;
import sjtu.ist.warehouse4ws.service.ModelgroupService;
import sjtu.ist.warehouse4ws.tool.FileIO;

public class RepositoryMoudl {
	private JcrTemplate template;
    private ModelgroupService modelgroupService;
    
    
	public void setModelgroupService(ModelgroupService modelgroupService) {
		this.modelgroupService = modelgroupService;
	}

	public void setTemplate(JcrTemplate template) {
		this.template = template;
	}

	// 创建公司节点
	public String createWorkSpace(final String companyId) {
		return (String) template.execute(new JcrCallback() {

			@Override
			public Object doInJcr(Session session) throws IOException,
					RepositoryException {
				String companyName = null;
				Node rn = session.getRootNode();
				if (!rn.hasNode(companyId)) {
					Node companyNode = rn.addNode(companyId); // 注册一个公司节点
					session.save();

					System.out.println("-----添加公司节点:" + companyNode.getName());

				} else {
					System.out.println("------已经存在公司的节点");

				}
				session.logout();
				return "success";
			}
		});
	}

	public String getFilePath() {
		return null;

	}

	// 添加模型节点框架
	public Value addModelNode(final String companyId, final String modelType) {
		return (Value) template.execute(new JcrCallback() {
			public Object doInJcr(Session session) throws IOException,
					RepositoryException {
				Node companyNode = session.getRootNode().getNode(companyId);
				if (!companyNode.hasNode(modelType)) {
					Node modelNode = companyNode.addNode(modelType); // 添加那一套模型
					modelNode.addMixin("mix:versionable"); // 给全套模型添加版本信息
					/*modelNode.addMixin("mix:lockable");
					modelNode.lock(true, false);
					modelNode.unlock();*/
					Node domainView = modelNode.addNode("domainView"); // 四个视图节点与项目文件节点
					Node functionView = modelNode.addNode("functionView");
					Node controlView = modelNode.addNode("controlView");
					Node orgView = modelNode.addNode("orgView");
					Node dataView = modelNode.addNode("dataView");
					Node projectFile = modelNode.addNode("projectFile");
					Node wsdl = modelNode.addNode("wsdl");
					Node wadl = modelNode.addNode("wadl");
					Node bpel = modelNode.addNode("bpel");
					Node bpmn = modelNode.addNode("bpmn");
					Node sla = modelNode.addNode("sla");

					domainView.setProperty("fileName", "领域视图");
					functionView.setProperty("fileName", "功能视图");
					controlView.setProperty("fileName", "控制视图");
					orgView.setProperty("fileName", "组织视图");
					dataView.setProperty("fileName", "数据视图");
					projectFile.setProperty("fileName", "项目视图");
					
					wsdl.setProperty("fileName", "wsdl");
					wadl.setProperty("fileName", "wadl");
					bpel.setProperty("fileName", "bpel");
					bpmn.setProperty("fileName", "bpmn");
					sla.setProperty("fileName", "sla");

				System.out.println("-----新生成一个模型树节点");	//数据视图直接存在dataView,项目文件直接存在projectFile里	
				session.save();



					Node models=domainView.addNode("models"); // 存业务对象模型的xml文件
					Node domainmodel=domainView.addNode("domainmodel"); // 存业务对象模型的建模文件
					// 其它文件存在domainView文件里

					models.setProperty("fileName", "models");
					domainmodel.setProperty("fileName", "领域模型");
				
			
				
					Node functions=functionView.addNode("functions"); // 存功能模型XML文件
					Node processes=functionView.addNode("processes"); // 存流程模型xml文件
					Node functionPoint=functionView.addNode("functionPoint"); // 存功能点.fp文件
					Node process=functionView.addNode("process"); // 存流程.process文件

					functions.setProperty("fileName", "functions");
					processes.setProperty("fileName", "processes");
					functionPoint.setProperty("fileName", "功能点");
					process.setProperty("fileName", "流程");
					
					Node bpel1=controlView.addNode("bpel");
					Node epc=controlView.addNode("epc");
					Node templates=controlView.addNode("templates"); // 其它文件存在controlView文件里

					bpel1.setProperty("fileName", "bpel");
					epc.setProperty("fileName", "epc");
					templates.setProperty("fileName", "templates");
					
					
					Node perms=orgView.addNode("perms");
					Node roles=orgView.addNode("roles"); // 其它文件存在orgView文件里
					perms.setProperty("fileName", "perms");
					roles.setProperty("fileName", "roles");
					
					System.out.println("-----新生成一个模型树节点"); // 数据视图直接存在dataView,项目文件直接存在projectFile里
					session.save();

				} else {

					System.out.println("-----已经存在模型节点框架");
				}

				session.logout();
				// System.out.print("---得到公司的节点"+companyNode.getName());
				// System.out.println("---添加模型类别节点和它下面的子节点"+companyNode.getNode("trafic").getName());
				return null;

			}

		});
	}

	// 导入整个模型到内容库
	public Value importAllModel(final String companyId, final String modelType,
			final ModelFilePojo mfp) {
		return (Value) template.execute(new JcrCallback() {
			public Object doInJcr(Session session) throws IOException,
					RepositoryException {

				String path = companyId + "/" + modelType;
				Node verNode = session.getRootNode().getNode(path);
				verNode.checkout();
				Node domainView = resetNode(verNode, "domainView");
				domainView.setProperty("fileName", "领域视图");
				Node functionView = resetNode(verNode, "functionView");
				functionView.setProperty("fileName", "功能视图");
				Node controlView = resetNode(verNode, "controlView");
				controlView.setProperty("fileName", "控制视图");
				Node orgView = resetNode(verNode, "orgView");
				orgView.setProperty("fileName", "组织视图");
				Node dataView = resetNode(verNode, "dataView");
				dataView.setProperty("fileName", "数据视图");
				Node projectFile = resetNode(verNode, "projectFile");
		//		projectFile.setProperty("fileName", "项目视图");

				Node models = domainView.addNode("models");
				Node domainmodel = domainView.addNode("domainmodel");
				
				models.setProperty("fileName", "models");
				domainmodel.setProperty("fileName", "领域模型");

				Node functions = functionView.addNode("functions");
				Node processes = functionView.addNode("processes");
				Node functionPoint = functionView.addNode("functionPoint");
				Node process = functionView.addNode("process");
				
				functions.setProperty("fileName", "functions");
				processes.setProperty("fileName", "processes");
				functionPoint.setProperty("fileName", "功能点");
				process.setProperty("fileName", "流程");
				
				Node bpel = controlView.addNode("bpel");
				Node epc = controlView.addNode("epc");
				Node templates = controlView.addNode("templates");
				
				bpel.setProperty("fileName", "bpel");
				epc.setProperty("fileName", "epc");
				templates.setProperty("fileName", "templates");

				Node perms = orgView.addNode("perms");
				Node roles = orgView.addNode("roles");
				
				perms.setProperty("fileName", "perms");
				roles.setProperty("fileName", "roles");
				
				if (!mfp.getDomainView().isEmpty()) {
					importModelList(session, domainView, mfp.getDomainView());
				}
				if (!mfp.getFunctionView().isEmpty()) {
					importModelList(session, functionView, mfp
							.getFunctionView());
				}
				if (!mfp.getControlView().isEmpty()) {
					importModelList(session, controlView, mfp.getControlView());
				}
				if (!mfp.getOrgView().isEmpty()) {
					importModelList(session, orgView, mfp.getOrgView());
				}
				if (!mfp.getDataView().isEmpty()) {
					importModelList(session, dataView, mfp.getDataView());
				}
				if (!mfp.getProjectFile().isEmpty()) {
					importProjectFile(session, projectFile, mfp
							.getProjectFile());
				}
				if (!mfp.getModels().isEmpty()) {
					importModelList(session, models, mfp.getModels());
				}
				if (!mfp.getDomainmodel().isEmpty()) {
					importModelList(session, domainmodel, mfp.getDomainmodel());
				}

				if (!mfp.getFunctions().isEmpty()) {
					importModelList(session, functions, mfp.getFunctions());
				}
				if (!mfp.getProcesses().isEmpty()) {
					importModelList(session, processes, mfp.getProcesses());
				}
				if (!mfp.getFunctionPoint().isEmpty()) {
					importModelList(session, functionPoint, mfp
							.getFunctionPoint());
				}
				if (!mfp.getProcess().isEmpty()) {
					importModelList(session, process, mfp.getProcess());
				}
				if (!mfp.getBpel().isEmpty()) {
					importModelList(session, bpel, mfp.getBpel());
				}
				if (!mfp.getEpc().isEmpty()) {
					importModelList(session, epc, mfp.getEpc());
				}
				if (!mfp.getTemplates().isEmpty()) {
					importModelList(session, templates, mfp.getTemplates());
				}
				if (!mfp.getPerms().isEmpty()) {
					importModelList(session, perms, mfp.getPerms());
				}
				if (!mfp.getRoles().isEmpty()) {
					importModelList(session, roles, mfp.getRoles());
				}
				session.save();
				verNode.checkin();
				session.logout();
				return null;
			}


		});
	}


	public Node resetNode(Node node,String arg) throws PathNotFoundException, RepositoryException{
		Node temp=node.getNode(arg);
		temp.remove();
		return node.addNode(arg);
	}
	//导入指定节点下的所有文件节点



	// 导入指定节点下的所有文件节点
	public void importModelList(Session session, Node node,
			final ArrayList<String> filepath) {

		try {
			for (int i = 0; i < filepath.size(); i++) {
				FileInputStream xml = new FileInputStream(filepath.get(i));
				File file = new File(filepath.get(i));
				String fileName = file.getName();

				Node fileNode = node.addNode(fileName);
				fileNode.setProperty("content", xml); // property no change
				fileNode.setProperty("fileName", fileName);
				fileNode.setProperty("time", Calendar.getInstance());


				session.save();
			


			}
			session.logout();
		} catch (Exception e) {

			e.printStackTrace();
			System.out.print("----------这里出问题2");
		}
	}

	// 导入指定节点下的单个文件
	public void importProjectFile(Session session, Node node,
			final String filepath) {

		try {

			FileInputStream xml = new FileInputStream(filepath);
			File file = new File(filepath);
			String fileName = file.getName();
			node.setProperty("content", xml);
			node.setProperty("fileName", fileName);
			node.setProperty("time", Calendar.getInstance());
			session.save();

		} catch (Exception e) {

			e.printStackTrace();
			System.out.print("----------这里出问题3");
		}
	}

	// 获取当前节点的最新版本
	public String getVersion(final String companyId, final String modelType) { // filepath由"companyId/modelType/xxView/节点名称--
		return (String) template.execute(new JcrCallback() {
			public Object doInJcr(Session session) throws IOException,
					RepositoryException {
				String filepath = companyId + "/" + modelType;
				Node fileNode = session.getRootNode().getNode(filepath);
				Version version = fileNode.checkin();
				VersionHistory vh = fileNode.getVersionHistory();
				VersionIterator vi = vh.getAllVersions();
				long a = vi.getSize() - 2;
				String ver = "1." + a;
				System.out.print(ver);
				session.logout();

				return ver; // 这个返回值会转换
			}

		});
	}

//测试版本
	public String testVersions(final String companyId, final String modelType) {
		return (String) template.execute(new JcrCallback() {
			public Object doInJcr(Session session) throws IOException,
					RepositoryException {
				String path = companyId + "/" + modelType;
				Node node = getFileNode(path, session);
				// node.checkin();
				try {
					String s=getVersionsPath(path).get(0);
					ArrayList<String> result=getNodesPathes(s);
					result=getNodesNames(result.get(4));
					for(int i=0;i<result.size();i++)
					{
						System.out.println(result.get(i));
						/*Node n=getFileNode(result.get(i),session);
						System.out.println(n.getName());
						NodeIterator ni=n.getNodes();
						while(ni.hasNext())
						{
							Node nv=ni.nextNode();
							if(nv.hasProperty("fileName"))System.out.println(nv.getName()+"="+nv.getProperty("fileName").getString());
						}*/
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// node.checkout();
				session.logout();
				return "success";
			}
		});
	}

	// 获取当前节点的版本信息
	public void getVertions(Node fileNode) throws Exception {
		Version version = fileNode.checkin();
		VersionHistory vh = fileNode.getVersionHistory();
		
		VersionIterator vi = vh.getAllVersions();

		vi.skip(1);
		Version v = null;
		Node nv = null;
		while (vi.hasNext()) { 
			

			NodeIterator ni = v.getNodes();
			while (ni.hasNext()) {
				nv = ni.nextNode();

			}
			NodeIterator models = nv.getNode("functionView/process").getNodes();
			while (models.hasNext()) {
				Node model = models.nextNode();
				// System.out.println(v.getName()+"版本   ");//
				System.out.println(model.getProperty("fileName").getString()); // 得到相应的文件
				// System.out.println(model.getProperty("content").getString());
				// //就可以生成文件流
			}
		}

	}

	public ArrayList<String> getVersions(final String companyId,
			final String modelType) {
		return getVersions(companyId + "/" + modelType);
	}

	public Node getFileNode(final String filepath, Session session)
			throws PathNotFoundException, RepositoryException { // filepath由"companyId/modelType/xxView/节点名称--
		System.out.println(filepath);
		Node node = session.getRootNode().getNode(filepath);
		session.logout();
		return node;
	}

	public Node getFileNodebyUUID(final String UUID, Session session)
			throws PathNotFoundException, RepositoryException { // filepath由"companyId/modelType/xxView/节点名称--
		System.out.println(UUID);
		Node node = session.getNodeByUUID(UUID);
		session.logout();
		return node;
	}
//获取点击事件文件的内容
	public String getModelXmlContent(final String path){
		return (String) template.execute(new JcrCallback() {

			public Object doInJcr(Session session) throws IOException,
					RepositoryException {
				Node node=session.getRootNode().getNode(path);
				String str=node.getProperty("content").getString();
				session.logout();
				return str;
			}
			
		});
		
	}
	//动态生成模型文件
	private void generatefile(InputStream fileinput,String docpath ,Node n) throws Exception {
		OutputStream output=new FileOutputStream(docpath+n.getProperty("fileName").getString());
		byte[] buffer=new byte[1024];
		int byteread=0;
		while((byteread=fileinput.read(buffer))!=-1){
			output.write(buffer, 0, byteread);
		}
		output.close();
	}
	//动态生成文件夹
	private void createDoc(String docpath,Node n) throws Exception{
		File f=new File(docpath+n.getProperty("fileName").getString());
        if (!(f.exists())) {
          f.mkdirs();
          System.out.println("----------生成文件成功");
          }
	}
	
	//生成文件，提供下载，提供全套模型的下载功能
	@SuppressWarnings("unchecked")	
	public 	ArrayList<InputStream> getModelXmlFile(final String path,final String docpath){  //path代表节点路径   docpath代表指定文件路径
		return (ArrayList<InputStream>) template.execute(new JcrCallback() {

			public Object doInJcr(Session session)  {

			try {
	//			String docpath="E:/apache-tomcat-6.0.35/webapps/WareHouse4WS/file/";  //可以传进来,生成文件存储所有模型文件
				File docfile=new File(docpath);
	            if (!(docfile.exists())) {
	            	docfile.mkdirs();
	              }
				Node node = session.getRootNode().getNode(path);
				NodeIterator ni = node.getNodes();
				while(ni.hasNext()){
					Node n=ni.nextNode();
					if(n.getProperty("fileName").getString().contains(".")){
						InputStream fileinput=n.getProperty("content").getStream();
						generatefile(fileinput,docpath,n);
			

					}else{
						createDoc(docpath,n);
						if(n.hasNodes()){
							NodeIterator ni1 = n.getNodes();
							while(ni1.hasNext()){
								Node n1=ni1.nextNode();
								if(n1.getProperty("fileName").getString().contains(".")){
									InputStream fileinput=n1.getProperty("content").getStream();
									String name=n.getProperty("fileName").getString();
									String docpath1=docpath+name+"/";
									generatefile(fileinput,docpath1,n1);
						

								}else{
									String name=n.getProperty("fileName").getString();
									String docpath1=docpath+name+"/";
									createDoc(docpath1,n1);
									if(n1.hasNodes()){
										NodeIterator ni2=n1.getNodes();
										while(ni2.hasNext()){
											Node n2=ni2.nextNode();
											if(n2.getProperty("fileName").getString().contains(".")){
												InputStream fileinput=n2.getProperty("content").getStream();
												String name1=n.getProperty("fileName").getString();
												String name2=n1.getProperty("fileName").getString();
												String docpath2=docpath+name1+"/"+name2+"/";
												generatefile(fileinput,docpath2,n2);
											

											System.out.println("-----------生成project成功");
											}
										}
									}
						
								}
							}
						}
					}

					
				}
			session.logout();
			} catch (PathNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (RepositoryException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch(Exception e){
				e.printStackTrace();
			}
	
				
				session.logout();
			
				return null;
			}
			
		});
	}
//显示可视化版本信息
	@SuppressWarnings("unchecked")		
	public ArrayList<VisionInfoPojo> showVersion(final String companyId, final String groupId,final int typeId,final String cid) { 
		return (ArrayList<VisionInfoPojo>) template.execute(new JcrCallback() {
			public ArrayList<VisionInfoPojo> doInJcr(Session session) throws IOException,
					RepositoryException {
				ArrayList<VisionInfoPojo> st=new ArrayList<VisionInfoPojo>();
				String filepath = companyId + "/" + groupId;
				Node fileNode = session.getRootNode().getNode(filepath);
				Version version = fileNode.checkin();
				VersionHistory vh = fileNode.getVersionHistory();
				VersionIterator vi = vh.getAllVersions();
				vi.skip(1);
				while (vi.hasNext()){                //版本迭代器  
					Version v = vi.nextVersion();   //得到版本
					NodeIterator ni = v.getNodes();
					while (ni.hasNext()) {
						Node nv = ni.nextNode();
						if(typeId==1){
							NodeIterator models = nv.getNode("orgView/roles").getNodes();						
							while (models.hasNext()) {
								Node model = models.nextNode();
								String name=model.getProperty("fileName").getString();
								String str=cid+".xml";
								if(model.getProperty("fileName").getString().equals(str)){
									VisionInfoPojo vif=new VisionInfoPojo();
									vif.setTime(model.getProperty("time").getString());
									vif.setGroupId(groupId);
									vif.setAuthor("superadmin");
									vif.setVersionId(v.getName());
									st.add(vif);
									break;
								}
							}
						}
								if(typeId==2){
									NodeIterator models1 = nv.getNode("domainView/models").getNodes();						
									while (models1.hasNext()) {
										Node model = models1.nextNode();
										String name=model.getProperty("fileName").getString();
										String str=cid+".xml";
										if(model.getProperty("fileName").getString().equals(str)){
											VisionInfoPojo vif=new VisionInfoPojo();
											vif.setTime(model.getProperty("time").getString());
											vif.setGroupId(groupId);
											vif.setAuthor("superadmin");
											vif.setVersionId(v.getName());
											st.add(vif);
											break;
										
										}
									
								
									}
								}
								if(typeId==3){
								NodeIterator models2 = nv.getNode("functionView/processes").getNodes();						
								while (models2.hasNext()) {
									Node model = models2.nextNode();
									String name=model.getProperty("fileName").getString();
									String str=cid+".xml";
									if(model.getProperty("fileName").getString().equals(str)){
										VisionInfoPojo vif=new VisionInfoPojo();
										vif.setTime(model.getProperty("time").getString());
										vif.setGroupId(groupId);
										vif.setAuthor("superadmin");
										vif.setVersionId(v.getName());
										st.add(vif);
										break;
									}
								//	System.out.println(model.getProperty("fileName").getString()); // 得到相应的文件
						
								}
								}
								if(typeId==4){
									NodeIterator models3 = nv.getNode("functionView/functions").getNodes();						
									while (models3.hasNext()) {
										Node model = models3.nextNode();
										String name=model.getProperty("fileName").getString();
										String str=cid+".xml";
										if(model.getProperty("fileName").getString().equals(str)){
											VisionInfoPojo vif=new VisionInfoPojo();
											vif.setTime(model.getProperty("time").getString());
 										    vif.setGroupId(groupId);
											vif.setAuthor("superadmin");
											vif.setVersionId(v.getName());
											st.add(vif);
											break;
										}
								//		System.out.println(model.getProperty("fileName").getString()); // 得到相应的文件
							
									}
									}
								if(typeId==5){
									NodeIterator models4 = nv.getNode("controlView/epc").getNodes();						
									while (models4.hasNext()) {
										Node model = models4.nextNode();
										String name=model.getProperty("fileName").getString();
										String str=cid+".epc";
										if(model.getProperty("fileName").getString().equals(str)){
											VisionInfoPojo vif=new VisionInfoPojo();
											vif.setTime(model.getProperty("time").getString());
											vif.setGroupId(groupId);
											vif.setAuthor("superadmin");
											vif.setVersionId(v.getName());
											st.add(vif);
											break;
										}
								//		System.out.println(model.getProperty("fileName").getString()); // 得到相应的文件
						
									}
				
							}
}
						
					}
			
		
		
				session.logout();
				return st;
			}

		});
	}

	@SuppressWarnings("unchecked")
	public ArrayList<String> getVersions(final String path) {
		return (ArrayList<String>) template.execute(new JcrCallback() {
			public ArrayList<String> doInJcr(Session session)
					throws IOException, RepositoryException {
				Node node = getFileNode(path, session);
				ArrayList<String> result = null;
				// node.checkin();
				try {
					result = getVertions1(node);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// node.checkout();
				session.logout();
				return result;
			}
		});
	}

	@SuppressWarnings("unchecked")
	public ArrayList<String> getVersionsPath(final String path) {
		return (ArrayList<String>) template.execute(new JcrCallback() {
			public ArrayList<String> doInJcr(Session session)
					throws IOException, RepositoryException {
				Node node = getFileNode(path, session);
				ArrayList<String> result = null;
				try {
					result = getVertionsPath(node);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// node.checkout();
				session.logout();
				return result;
			}
		});
	}
//获取某个节点下所有子节点的名字
	@SuppressWarnings("unchecked")
	public ArrayList<String> getNodesNames(final String path) {
		return (ArrayList<String>) template.execute(new JcrCallback() {
			public ArrayList<String> doInJcr(Session session)
					throws IOException, RepositoryException {
				Node rn = session.getRootNode().getNode(path);
				ArrayList<String> result = new ArrayList<String>();
				NodeIterator ni = rn.getNodes();
				while (ni.hasNext()) {
					Node n = ni.nextNode();
						if(n.hasProperty("fileName"))result.add(n.getProperty("fileName").getString());
						else result.add(n.getName());
				}
				session.logout();
				return result;
			}
		});
	}
//获取某个节点下，所有子节点的路径
	@SuppressWarnings("unchecked")
	public ArrayList<String> getNodesPathes(final String path) {
		return (ArrayList<String>) template.execute(new JcrCallback() {
			public ArrayList<String> doInJcr(Session session)
					throws IOException, RepositoryException {
				Node rn = session.getRootNode().getNode(path);
				ArrayList<String> result = new ArrayList<String>();
				NodeIterator ni = rn.getNodes();
				while (ni.hasNext()) {
					Node n = ni.nextNode();
					result.add(n.getPath().substring(1));
				}
				session.logout();
				return result;

			}
		});
	}
	
	
	@SuppressWarnings("unchecked")
	public String getNodePath(final String companyId,final String modelType,final String versionId) {
		return (String)template.execute(new JcrCallback() {
			public String doInJcr(Session session)
					throws IOException, RepositoryException {
				String path=companyId+"/"+modelType;
				Node node = session.getRootNode().getNode(path);
				VersionHistory vh = node.getVersionHistory();
				Version v = vh.getVersion(versionId);
				NodeIterator ni=v.getNodes();
				Node n=ni.nextNode();
//				vi.skip(1);
//				while (vi.hasNext()) {
//					Version v = vi.nextVersion();
//					if(v.getName().equals(versionId)){
//						System.out.println(v.getPath().substring(1));
//						return v.getPath().substring(1);
//					}
//				}
				
			
				session.logout();
				System.out.println("node.getpath:"+n.getPath());
				return n.getPath().substring(1);

			}
		});
	}

	@SuppressWarnings("unchecked")
	public Value addServiceFile(final String companyId,final String modelType,final String versionId, final String type,final List<String> p) {
		return (Value)template.execute(new JcrCallback() {
			public Value doInJcr(Session session)
					throws IOException, RepositoryException {
				String path=companyId+"/"+modelType;
				Node node = session.getRootNode().getNode(path);
//				VersionHistory vh = node.getVersionHistory();
//				Version v = vh.getVersion(versionId);
//				NodeIterator ni=v.getNodes();
//				Node n=ni.nextNode();
				node.checkout();
				
				Node wsdl=node.getNode(type);
				for (String i:p)
				{
					FileInputStream xml = new FileInputStream(i);
					File file = new File(i);
					String fileName = file.getName();

					Node fileNode = wsdl.addNode(fileName);
					fileNode.setProperty("content", xml); // property no change
					fileNode.setProperty("fileName", fileName);
					fileNode.setProperty("time", Calendar.getInstance());

				}
				
				session.save();
				node.checkin();
			    session.logout();
//			    Modelgroup modelgroup=new Modelgroup();
//				modelgroup.setGroupName(modelType);
//				modelgroup.setVersion(versionId+0.1); //最新版本
//				modelgroupService.save(modelgroup);
				     //add version info to DB;
				return null;

			}
		});
	}
	@SuppressWarnings("unchecked")
	public HashMap<String,String> getAllFile(final String companyId,final String modelType,final String versionId, final String type) {
		return (HashMap<String, String>)template.execute(new JcrCallback() {
			public HashMap<String, String> doInJcr(Session session)
					throws IOException, RepositoryException {
				String path=companyId+"/"+modelType;
				Node node = session.getRootNode().getNode(path);
				VersionHistory vh = node.getVersionHistory();
				Version v = vh.getVersion(versionId);
				NodeIterator ni=v.getNodes();
				Node n=ni.nextNode();
				String filepath="";
				if (type.equals("domain"))
				filepath="domainView/models";
				//这里以后修改
				else if(type.equals("function")) 
					filepath="functionView/functions";     
				else filepath="controlView/epc";
				ni=n.getNode(filepath).getNodes();
                HashMap<String,String> fs=new HashMap<String,String>();
				while (ni.hasNext()) {
					 n = ni.nextNode();
					 String key=n.getProperty("fileName").getString();
					 InputStream is=n.getProperty("content").getStream();
					 StringBuffer  sbis   =  new  StringBuffer();
					 int b;
					 while((b=is.read())!=-1){ 
					        sbis.append((char)b);
					} 

					String value=sbis.toString();
					 fs.put(key, value);
					 
				}
				
			    
				session.logout();
				System.out.println("node.getpath:"+n.getPath());
				return fs;

			}
		});
	}

	// 获取版本节点的版本信息
	public ArrayList<String> getVertions1(Node fileNode) throws Exception {
		VersionHistory vh = fileNode.getVersionHistory();
		VersionIterator vi = vh.getAllVersions();
		// System.out.println(vh.getVersionLabels().length);
		ArrayList<String> result = new ArrayList<String>();
		vi.skip(1);
		while (vi.hasNext()) {
			Version v = vi.nextVersion();
			
			result.add(v.getName());
			System.out.println(v.getName() + "版本   ");

		}
		return result;
	}
//获取版本节点的路径
	public ArrayList<String> getVertionsPath(Node fileNode) throws Exception {
		VersionHistory vh = fileNode.getVersionHistory();
		VersionIterator vi = vh.getAllVersions();
		// System.out.println(vh.getVersionLabels().length);
		ArrayList<String> result = new ArrayList<String>();
		vi.skip(1);
		while (vi.hasNext()) {
			Version v = vi.nextVersion();
			NodeIterator ni = v.getNodes();
			while (ni.hasNext()) {
				Node node = ni.nextNode();
				result.add(node.getPath().substring(1));
			}
		}
		return result;
	}
	public String removeNode(final String path) {
		return (String) template.execute(new JcrCallback() {
			public String doInJcr(Session session)throws IOException, RepositoryException {
				session.getRootNode().getNode(path).remove();
				session.save();
				return null;
			}
			});
			}
	
	/**
	 * 把模型文件存入文件库
	 * path:文件夹路径，文件夹中包含所有模型文件
	 * companyId:租户id
	 * groupName:模型组名
	 * */
	public void saveModelgroup(String path, String companyId, String groupName){
		System.out.println("文件库："+groupName);
		this.createWorkSpace(companyId);
		this.addModelNode(companyId,groupName);
		FileIO fio=new FileIO();
		ModelFilePojo mfp=fio.getAllModelData(path);
		this.importAllModel(companyId, groupName, mfp);
		System.out.print("------------导入模型成功");
	}
}
